#include<bits/stdc++.h>
#define int long long
#define ls(x) ((x)*2)
#define rs(x) ((x)*2+1)
#define Debug(...) fprintf(stderr, __VA_ARGS__)
#define For(i,a,b) for(int i=a,i##end=b;i<=i##end;i++)
#define Rof(i,a,b) for(int i=a,i##end=b;i>=i##end;i--)
#define rep(i,  b) for(int i=1,i##end=b;i<=i##end;i++)
using namespace std;
const int N=1e6+5,base=999983;
int Mod;
char buf[(1<<21)+5],*p1,*p2;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
inline void chmx(int &x,int y){(x<y)&&(x=y);}
inline void chmn(int &x,int y){(x>y)&&(x=y);}
inline void Add(int &x,int y){(x=x+y+Mod)%=Mod;}
inline int read(){
	int f=0,x=0;
	char ch=getchar();
	while(!isdigit(ch)){f|=(ch=='-');ch=getchar();}
	while(isdigit(ch)){x=(x<<3)+(x<<1)+(ch^48);ch=getchar();}
	return f?-x:x;
}
void print(int n){
    if(n<0){
        putchar('-');
        n*=-1;
    }
    if(n>9) print(n/10);
    putchar(n%10+'0');
}
int n;
int a[1005][1005];
int b[1005][1005];
int c[1005][1005];
int z[1005],zz[1005];
int y1[1005],y2[1005];
signed main(){
	freopen("matrix.in","r",stdin);
	freopen("matrix.out","w",stdout);
	// ios::sync_with_stdio(false);
	// cin.tie(0); cout.tie(0);
	srand(time(0));
	 int T=read();
	while(T--){
		Mod=read();
		n=read();
		if(Mod==1){
			puts("Yes");
			continue;
		}
		For(i,1,n) For(j,1,n) a[i][j]=read()%Mod;
		For(i,1,n) For(j,1,n) b[i][j]=read()%Mod;
		For(i,1,n) For(j,1,n) c[i][j]=read()%Mod;
		if(n<=300){
			bool flag=1;
			For(i,1,n){
				For(j,1,n){
					int res=0;
					For(k,1,n) (res+=a[i][k]*b[k][j])%=Mod;
					flag&=(c[i][j]%Mod==res%Mod) ;
				}
			}if(flag)puts("Yes");
			else puts("No"); 
			continue;
		}
		int flag=1;
		For(Test,1,15){
			For(i,1,n) y1[i]=0,z[i]=rand()%(Mod-1)+1;
			For(i,1,n){
				For(j,1,n){
					y1[j]+=(z[i]*a[i][j])%Mod;
				}
			}
			For(i,1,n) zz[i]=y1[i]%Mod,y1[i]=0;
			For(i,1,n){
				For(j,1,n){
					y1[j]+=(zz[i]*b[i][j])%Mod;
				}
			}
			For(i,1,n) y2[i]=0;
			For(i,1,n){
				For(j,1,n){
					y2[j]+=(z[i]*c[i][j])%Mod;
				}
			}
			For(i,1,n) flag&=(y1[i]%Mod==y2[i]%Mod);
			if(!flag) break;
		}
		if(flag) puts("Yes");
		else puts("No");
	}
#ifdef LOCAL
    Debug("\nMy Time: %.3lfms\n", (double)clock() / CLOCKS_PER_SEC);
#endif
	return 0;
}

